----------------------------------------------------------------------------------
-- INSTITUTION:    Xidian University
-- DESIGNER:       Yuan Xiaoguang & Ren Aifeng    
-- 
-- Create Date:    16:53:58 02-14-2016 
-- Design Name:    FREQUENCY_DIVIDER 
-- Module Name:    FREQUENCY_DIVIDER 
-- Project Name:   PWM
-- Target Devices: EP3C16F484C6
-- Tool versions:  Quartus II 13.1
-- Design Lauguage:VHDL
-- Dependencies:   -
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: DE0 Board Input Freguency = 50 MHz
--                      Destiny Output  Freguency =  1 Hz
--分频器
----------------------------------------------------------------------------------

library IEEE;       --库声明
use IEEE.std_logic_1164.all;       --使用程序包
use IEEE.std_logic_arith.all;
use IEEE.std_logic_unsigned.all;

entity FREQUENCY_DIVIDER is         --定义分频器实体
	generic(
		sys_clk_fre_value: INTEGER := 50000000;      --系统时钟频率值
		div_clk_fre_value: INTEGER := 5000           --分频器输出期望值，5000Hz。所以是10000分频
	);
	port(                                           --定义输入输出端口
		i_sys_clk: in STD_LOGIC;                     --系统时钟输入，位逻辑类型
		i_sys_rst: in STD_LOGIC;	                  --系统复位输入
		o_div_clk: out STD_LOGIC	                  --分频时钟输出
	);
end entity FREQUENCY_DIVIDER;

architecture behavior of FREQUENCY_DIVIDER is 
	signal r_div_count: STD_LOGIC_VECTOR (31 downto 0);      --计数器寄存器，位逻辑类型，32位，计分频器模值
	signal r_div_clk:STD_LOGIC;                              --分频时钟暂存
begin
	process(i_sys_rst,i_sys_clk)	
		begin
		if (i_sys_rst = '1') then	        --当输入系统复位高有效时
				r_div_count <= x"00000000";  --清零计数器寄存器（进制）7
				r_div_clk <= '0';            --清零输出分频时钟
			elsif (i_sys_clk'event AND i_sys_clk = '1') then	
				if (r_div_count = sys_clk_fre_value/div_clk_fre_value/2-1) then      --达到分频器模值
					r_div_count <=  x"00000000";           --清零计数器寄存器
					r_div_clk <= NOT r_div_clk;            --翻转分频时钟暂存，从高电平翻转到低电平，实现分频，e.g.2分频时计数器计数到2时就从高电平翻转为低电平
				else
					r_div_count <= r_div_count+1;          --没达到分频器模值的，计数器+1
				end if;
			end if;
	end process;
	o_div_clk <= r_div_clk;       --将分频时钟暂存值复制到分频时钟输出
end architecture behavior;
